from shuangti.Item01.AIAssistant import AIAssistant


class AIManager:
    """AI助手管理器，处理助手的添加、查询、修改、删除、任务分配等逻辑"""
    def __init__(self, capacity: int = 10):
        """初始化固定大小的存储列表（默认容量10）"""
        if capacity <= 0:
            raise ValueError("存储容量必须大于0")
        self.capacity = capacity
        self.assistants = [None] * capacity  # 固定大小列表（模拟数组）
        self.current_count = 0  # 当前存储的助手数量

    def add_assistant(self, assistant: AIAssistant) -> str:
        """添加新AI助手"""
        # 校验容量是否已满
        if self.current_count >= self.capacity:
            return "❌ 系统容量不足，无法添加新助手"
        # 校验ID是否重复
        if self.get_assistant_by_id(assistant.aid):
            return f"❌ ID为{assistant.aid}的助手已存在，添加失败"
        # 添加到列表
        self.assistants[self.current_count] = assistant
        self.current_count += 1
        return f"✅ 助手【{assistant.name}】添加成功！"

    def get_assistant_by_id(self, aid: str) -> AIAssistant | None:
        """根据ID查询助手"""
        for i in range(self.current_count):
            if self.assistants[i].aid == aid:
                return self.assistants[i]
        return None

    def get_all_assistants(self) -> list[AIAssistant]:
        """获取所有AI助手列表"""
        return self.assistants[:self.current_count]  # 返回已存储的助手（过滤None）

    def update_assistant(self, aid: str, property_: str, value: str) -> str:
        """根据ID修改助手信息"""
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            return f"❌ 未找到ID为{aid}的助手，修改失败"

        # 处理不同属性的修改逻辑
        try:
            property_ = property_.lower()
            if property_ == "name":
                assistant.name = value
            elif property_ == "type":
                assistant.type_ = value
            elif property_ == "version":
                assistant.version = value
            elif property_ == "online":
                # 1-在线，0-离线
                if value not in ["0", "1"]:
                    return "❌ online属性值必须为0（离线）或1（在线）"
                assistant.is_online = (value == "1")
            elif property_ == "score":
                # 能力评分需转为整数并校验范围
                score = int(value)
                if 0 <= score <= 100:
                    assistant.ability_score = score
                else:
                    return "❌ 能力评分必须在0-100之间"
            else:
                return "❌ 可修改属性列表为：name,type,version,online,score"
            return f"✅ 助手【{aid}】修改成功！"
        except ValueError:
            return f"❌ 修改失败：参数格式错误（如score需为数字）"

    def delete_assistant(self, aid: str) -> str:
        """根据ID删除助手"""
        # 查找助手索引
        delete_index = -1
        for i in range(self.current_count):
            if self.assistants[i].aid == aid:
                delete_index = i
                deleted_name = self.assistants[i].name
                break
        if delete_index == -1:
            return f"❌ 未找到ID为{aid}的助手，删除失败"

        # 移除助手（列表元素前移，模拟数组删除）
        for i in range(delete_index, self.current_count - 1):
            self.assistants[i] = self.assistants[i + 1]
        self.assistants[self.current_count - 1] = None  # 清空最后一个位置
        self.current_count -= 1
        return f"✅ 助手【{deleted_name}】已删除。"

    def start_assistant(self, aid: str) -> str:
        """启动AI助手服务（设置为在线）"""
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            return f"❌ 未找到ID为{aid}的助手，启动失败"
        if assistant.is_online:
            return f"助手【{assistant.name}】已在运行。"
        assistant.is_online = True
        return f"✅ 助手【{assistant.name}】已启动。"

    def stop_assistant(self, aid: str) -> str:
        """停止AI助手服务（设置为离线）"""
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            return f"❌ 未找到ID为{aid}的助手，停止失败"
        if not assistant.is_online:
            return f"助手【{assistant.name}】已停止。"
        assistant.is_online = False
        return f"✅ 助手【{assistant.name}】已停止。"

    def assign_task(self, aid: str, task_content: str) -> str:
        """为AI助手分配任务"""
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            return f"❌ 未找到ID为{aid}的助手，无法分配任务"
        # 调用助手的execute_task方法执行任务
        return assistant.execute_task(task_content)

    def get_system_stats(self) -> str:
        """获取系统统计信息"""
        if self.current_count == 0:
            return ("系统统计信息：\n总助手数: 0\n在线助手数: 0\n"
                    "离线助手数: 0\n平均能力评分: 0.00")

        # 统计在线数量与总评分
        online_count = 0
        total_score = 0
        for i in range(self.current_count):
            assistant = self.assistants[i]
            if assistant.is_online:
                online_count += 1
            total_score += assistant.ability_score

        # 计算平均评分（保留2位小数）
        avg_score = total_score / self.current_count
        return (f"系统统计信息：\n总助手数: {self.current_count}\n"
                f"在线助手数: {online_count}\n离线助手数: {self.current_count - online_count}\n"
                f"平均能力评分: {avg_score:.2f}")

    def get_capacity_info(self) -> str:
        """获取系统容量信息"""
        return f"系统容量：{self.current_count}/{self.capacity}（已用/总容量）"